<template>
  <view class="quick-release-container">
    

    <view class="form-container">
      <view class="form-item">
        <text class="label">任务描述</text>
        <textarea 
          v-model="form.title" 
          placeholder="例如：帮忙送文件到行政楼"
          auto-height
          maxlength="50"
        />
      </view>

      <view class="form-item">
        <text class="label">悬赏金额(元)</text>
        <input 
          v-model="form.reward" 
          type="number" 
          placeholder="输入金额"
        />
      </view>

      <view class="form-item">
        <text class="label">期望完成时间 *</text>
        <view class="select-container" @tap="handleSelectDeliveryTime">
          <view class="select-input" :class="{ 'has-value': form.expectedTime }">
            <text v-if="!form.expectedTime">请选择完成时间</text>
            <text v-else>{{ form.expectedTime }}</text>
          </view>
          <uni-icons type="right" size="16" color="#999999" />
        </view>
      </view>

      <!-- 时间选择器弹窗 -->
      <uni-popup ref="timePicker" type="bottom" @change="handleCloseTimePicker">
        <view class="time-picker-container">
          <view class="time-picker-header">
            <text class="time-picker-title">选择完成时间</text>
            <view class="time-picker-close" @tap="handleCloseTimePicker">
              <uni-icons type="close" size="20" color="#999999" />
            </view>
          </view>
          <scroll-view scroll-y class="time-slots-list">
            <view 
              v-for="(time, index) in timeSlots" 
              :key="index"
              class="time-slot-item"
              :class="{ 'selected': time === form.expectedTime }"
              @tap="handleTimeSelect(time)"
            >
              <text>{{ time }}</text>
              <uni-icons 
                v-if="time === form.expectedTime" 
                type="checkmarkempty" 
                size="16" 
                color="#3B7FF3" 
              />
            </view>
          </scroll-view>
        </view>
      </uni-popup>

      <view class="form-item">
        <text class="label">手机号（可选）</text>
        <input 
          v-model="form.contact" 
          type="number"
          placeholder="请输入手机号"
          maxlength="11"
        />
        <text class="hint">不填写将使用您的默认手机号</text>
      </view>

      <view class="form-item">
        <text class="label">加急任务</text>
        <switch :checked="form.isUrgent" @change="form.isUrgent = $event.detail.value" />
        <text class="hint">加急任务将额外收取30%的发布费用</text>
      </view>

      <button class="submit-btn" @tap="handleSubmit">立即发布</button>
    </view>

    <!-- 支付弹窗 -->
    <PaymentModal 
      ref="paymentModal"
      :reward="Number(form.reward)"
      :baseFee="basePublishFee"
      :urgentFee="urgentPublishFee"
      :taskInfo="paymentTaskInfo"
      @success="handlePaymentSuccess"
      @cancel="handlePaymentCancel"
    />
  </view>
</template>

<script>
import PaymentModal from '@/components/PaymentModal.vue'
import { normalizeTaskData, validateTaskData, debugTaskData } from '@/utils/taskDataMapper.js'
import { taskErrorHandler, TaskDebugger, DataRepairTool } from '@/utils/taskErrorHandler.js'

export default {
  components: {
    PaymentModal
  },
  data() {
    return {
      form: {
        title: '',
        reward: '',
        expectedTime: '', // 期望完成时间
        contact: '', // 联系方式
        isUrgent: false
      },
      userInfo: null,
      // 时间选择相关
      timeSlots: [
        '1小时内',
        '2小时内', 
        '3小时内',
        '6小时内',
        '12小时内',
        '24小时内',
        '2天内',
        '3天内',
        '1周内'
      ],
      showTimePicker: false,
      // 支付相关
      basePublishFee: 3, // 基础发布费3元
      urgentPublishFee: 0, // 加急发布费
      paymentTaskInfo: {}, // 支付任务信息
      pendingTaskData: null, // 待发布的任务数据
    }
  },

  onShow() {
    let userInfo = uni.getStorageSync('uni-id-pages-userInfo');
    console.log('--- Debugging onShow ---');
    console.log('1. Raw userInfo from storage:', userInfo);
    console.log('2. Type of raw userInfo:', typeof userInfo);

    if (typeof userInfo === 'string') {
      try {
        userInfo = JSON.parse(userInfo);
        console.log('3. Parsed userInfo:', userInfo);
        console.log('4. Type of parsed userInfo:', typeof userInfo);
      } catch (e) {
        console.error('5. Error parsing userInfo:', e);
        userInfo = null;
      }
    }

    console.log('6. Final userInfo before check:', userInfo);
    if (userInfo && userInfo._id) {
      this.userInfo = {
        _id: userInfo._id,
        username: userInfo.username,
        nickname: userInfo.nickname || userInfo.username || '用户',
        avatar: (userInfo.avatar_file && userInfo.avatar_file.url) 
                  ? userInfo.avatar_file.url 
                  : (userInfo.avatar || '/static/images/default_avatar.png'),
        phone: userInfo.mobile || userInfo.phone || userInfo.phoneNumber || '',
        wechat: userInfo.wechat || userInfo.weixin || ''
      };
      console.log('11. User is logged in. ID:', this.userInfo._id, 'Avatar:', this.userInfo.avatar);
      console.log('12. User contact info - Phone:', this.userInfo.phone, 'Wechat:', this.userInfo.wechat);
      
      // 设置智能默认值
      this.setSmartDefaults();
    } else {
      console.log('10. Condition `!userInfo || !userInfo._id` is TRUE. Redirecting...');
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateTo({
          url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
        });
      }, 1500);
      return;
    }
    console.log('--- End Debugging onShow ---');
  },

  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    // 设置智能默认值
    setSmartDefaults() {
      // 设置默认手机号
      if (this.userInfo && this.userInfo.phone) {
        this.form.contact = this.userInfo.phone;
      }
    },
    
    // 格式化日期时间
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    
    // 处理选择完成时间
    handleSelectDeliveryTime() {
      this.showTimePicker = true;
      this.$nextTick(() => {
        this.$refs.timePicker.open('bottom');
      });
    },

    handleTimeSelect(time) {
      this.form.expectedTime = time;
      this.showTimePicker = false;
    },

    handleCloseTimePicker() {
      this.showTimePicker = false;
    },
    
    // 验证手机号格式
    isValidPhone(phone) {
      const phoneRegex = /^1[3-9]\d{9}$/;
      return phoneRegex.test(phone);
    },
    
    handleSubmit() {
      // 表单验证
      if (!this.form.title) {
        uni.showToast({ title: '请输入任务标题', icon: 'none' })
        return
      }
      if (!this.form.reward || Number(this.form.reward) <= 0) {
        uni.showToast({ title: '请输入有效金额', icon: 'none' })
        return
      }
      if (!this.form.expectedTime) {
        uni.showToast({ title: '请选择期望完成时间', icon: 'none' })
        return
      }
      
      // 验证手机号格式（如果填写了）
      if (this.form.contact && !this.isValidPhone(this.form.contact)) {
        uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
        return
      }

      // 计算发布费用
      this.calculatePublishFee()

      // 准备任务数据 - 使用统一的数据结构
      const rawTaskData = {
        id: `other_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`, // 生成唯一ID
        type: 'other',
        title: this.form.title,
        description: '',
        reward: Number(this.form.reward),
        status: 'pending',
        publisher_id: this.userInfo._id,
        publisher_name: this.userInfo.nickname,
        publisher_avatar: this.userInfo.avatar,
        publish_time: new Date(),
        expected_delivery_time: this.form.expectedTime,
        contact_info: this.form.contact || this.userInfo.phone || '',
        contact_name: this.userInfo.nickname || '发布者',
        contact_phone: this.form.contact || this.userInfo.phone || '',
        is_urgent: this.form.isUrgent || false,
        tags: this.form.isUrgent ? ['urgent'] : [],
      }

      // 标准化任务数据
      this.pendingTaskData = normalizeTaskData(rawTaskData, 'other')
      
      // 调试信息
      console.log('[快速发布] 原始数据:', rawTaskData)
      console.log('[快速发布] 标准化后数据:', this.pendingTaskData)
      console.log('[快速发布] 任务类型:', this.pendingTaskData.type)
      console.log('[快速发布] 期望完成时间:', this.pendingTaskData.expectedDeliveryTime)
      console.log('[快速发布] 联系方式信息:')
      console.log('  - contact_info:', this.pendingTaskData.contactInfo)
      console.log('  - contact_name:', this.pendingTaskData.contactName)
      console.log('  - contact_phone:', this.pendingTaskData.contactPhone)
      console.log('  - 用户手机号:', this.userInfo.phone)
      console.log('  - 表单联系方式:', this.form.contact)
      
      // 验证数据完整性
      const validation = validateTaskData(this.pendingTaskData)
      if (!validation.isValid) {
        console.error('[快速发布] 数据验证失败:', validation.errors)
        console.error('[快速发布] 验证失败的数据:', this.pendingTaskData)
        uni.showToast({
          title: '数据验证失败，请重试',
          icon: 'none'
        })
        return
      }

      // 调试信息
      debugTaskData(this.pendingTaskData, '快速发布')

      // 设置支付任务信息
      this.paymentTaskInfo = {
        id: this.pendingTaskData.id, // 添加任务ID
        title: this.pendingTaskData.title,
        description: `任务描述：${this.form.title}\n期望完成时间：${this.form.expectedTime}\n联系方式：${this.form.contact || '请私聊联系'}`,
        type: 'other',
        baseFee: this.basePublishFee // 添加基础费用
      }

      // 显示支付弹窗
      this.$refs.paymentModal.show()
    },

    // 计算发布费用
    calculatePublishFee() {
      this.basePublishFee = 3 // 基础发布费3元
      this.urgentPublishFee = this.form.isUrgent ? Math.round(this.basePublishFee * 0.3) : 0 // 加急费30%
    },

    // 支付成功回调
    async handlePaymentSuccess(paymentInfo) {
      try {
        uni.showLoading({
          title: '发布中...'
        })

        // 添加支付信息到任务数据
        this.pendingTaskData.payment_id = paymentInfo.paymentId
        this.pendingTaskData.payment_amount = paymentInfo.amount
        this.pendingTaskData.payment_method = paymentInfo.method

        // 调用云函数发布任务
        const res = await uniCloud.callFunction({
          name: 'addTask',
          data: {
            taskData: this.pendingTaskData
          }
        })

        uni.hideLoading()

        if (res.result.code === 200) {
          uni.showToast({
            title: '发布成功',
            icon: 'success'
          })
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/index/index'
            })
          }, 1500)
        } else {
          uni.showToast({
            title: res.result.msg || '发布失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '发布失败，请重试',
          icon: 'none'
        })
        console.error('发布任务失败：', error)
      }
    },

    // 支付取消回调
    handlePaymentCancel() {
      this.pendingTaskData = null
      this.paymentTaskInfo = {}
    },

    getCurrentUser() {
      let userInfo = uni.getStorageSync('uni-id-pages-userInfo');
      let parsedInfo = {};

      if (userInfo === '[object Object]') {
        console.warn("localStorage 'uni-id-pages-userInfo' contained the literal string '[object Object]'. Defaulting to anonymous user.");
        parsedInfo = {}; // Treat as empty or invalid data
      } else if (typeof userInfo === 'string') {
        try {
          parsedInfo = JSON.parse(userInfo);
        } catch (e) {
          console.error("Error parsing userInfo from localStorage as JSON:", e);
          parsedInfo = {}; // Fallback if parsing fails
        }
      } else if (typeof userInfo === 'object' && userInfo !== null) {
        // If userInfo is already an object, use it directly
        parsedInfo = userInfo;
      }
      
      // Ensure parsedInfo is always a valid object for property access
      if (typeof parsedInfo !== 'object' || parsedInfo === null) {
        parsedInfo = {};
      }

      return {
        id: parsedInfo.uid || 'anonymous',
        nickname: parsedInfo.nickname || parsedInfo.username || '匿名用户',
        avatar: (parsedInfo.avatar_file && parsedInfo.avatar_file.url) ? parsedInfo.avatar_file.url : '/static/images/avatar1.png'
      };
    }
  }
}
</script>

<style scoped>
.quick-release-container {
  padding: 20rpx;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  font-size: 18px;
  font-weight: bold;
}

.form-container {
  margin-top: 40rpx;
}

.form-item {
  margin-bottom: 40rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.label {
  display: block;
  margin-bottom: 20rpx;
  font-size: 16px;
  color: #333;
}

textarea, input {
  width: 100%;
  font-size: 16px;
  padding: 10rpx 0;
}

.submit-btn {
  margin-top: 60rpx;
  background: linear-gradient(135deg, #3498db, #9b59b6);
  color: white;
  border-radius: 50rpx;
}

/* 新增样式 */
.picker-text {
  padding: 20rpx 0;
  font-size: 16px;
  color: #333;
  border-bottom: 1rpx solid #eee;
}

.picker-text.placeholder {
  color: #999;
}

.hint {
  display: block;
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #999;
  line-height: 1.4;
}

.form-item {
  position: relative;
}

.form-item .label {
  font-weight: 500;
}

.form-item .label::after {
  content: '';
  display: inline-block;
  width: 0;
  height: 0;
}

/* 时间选择器样式 */
.select-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.select-input {
  flex: 1;
  font-size: 16px;
  color: #999;
}

.select-input.has-value {
  color: #333;
}

.time-picker-container {
  background: white;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 60vh;
}

.time-picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.time-picker-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.time-picker-close {
  padding: 10rpx;
}

.time-slots-list {
  max-height: 400rpx;
}

.time-slot-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
  transition: background-color 0.2s;
}

.time-slot-item:active {
  background-color: #f5f5f5;
}

.time-slot-item.selected {
  background-color: #f0f7ff;
  color: #3B7FF3;
}

.time-slot-item text {
  font-size: 30rpx;
  color: inherit;
}
</style>